package com.robot.mannge.common.utils.jwt;

import com.robot.mannge.auth.domain.vo.SysUserVO;
import com.robot.mannge.common.exception.KabobExceptionUtil;
import com.robot.mannge.common.result.ResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Smile
 * @Date: 2024/01/30/16:46
 * @Description:
 */
@Data
@Component
//@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    @Value("${jwt.pubkey}")
    private String secret;

    @Value("${jwt.expireTime}")
    private Long expireTime;

    /**
     * 生成令牌
     * @param claims
     * @return
     */
    private String generateToken(Map<String,Object> claims){
        Date expirationDate = new Date(System.currentTimeMillis() + expireTime);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512,secret).compact();
    }

    /**
     * 解析令牌
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            claims = null;
        }
        return claims;
    }

    /**
     * 创建令牌
     * @param userDetails
     * @return
     */
    public String createToken(UserDetails userDetails){
        Map<String, Object> map = new HashMap<>();
        map.put(Claims.SUBJECT,userDetails.getUsername());
        map.put(Claims.ISSUED_AT,new Date());
        return generateToken(map);

    }

    /**
     * 从令牌中获取用户名
     * @param token
     * @return
     */
    public String getUserNameFromToke(String token){
        String username;
        try {
            Claims claimsFromToken = getClaimsFromToken(token);
            username = claimsFromToken.getSubject();
        }catch (Exception e){
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     * @param token
     * @return
     */
    public Boolean isTokenExpired(String token){
        Claims claimsFromToken = getClaimsFromToken(token);
        Date expiration = claimsFromToken.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 刷新令牌
     * @param token
     * @return
     */
    public String refreshToken(String token){
        String refreshToken;

        try {
            Claims claimsFromToken = getClaimsFromToken(token);
            claimsFromToken.put(Claims.ISSUED_AT,new Date());
            refreshToken = generateToken(claimsFromToken);
        }catch (Exception e){
            refreshToken = null;
        }

        return refreshToken;
    }

    /**
     * 验证令牌
     * @param token
     * @param userDetails
     * @return
     */
    public Boolean validateToken(String token,UserDetails userDetails){
        SysUserVO sysUserVO = (SysUserVO) userDetails;
        String userName = getUserNameFromToke(token);
        return (userName.equals(sysUserVO.getUsername()) && !isTokenExpired(token));
    }

}
